package com.minelx.statementsplus;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class Proxy {
	private final JSONObject provinces;

	private Proxy(JSONObject provinces) {
		this.provinces = provinces;
	}

	public List<Proxy> children() {
		return provinces.getJSONArray("children").stream()
				.map(item -> ((JSONObject) item))
				.map(Proxy::create)
				.collect(toList());
	}

	public String name() {
		return provinces.getString("name");
	}

	public int code() {
		return provinces.getIntValue("code");
	}

	public Proxy path(int... proxyIds) {
		Proxy result = this;
		for (int proxyId : proxyIds) {
			result = result.children().stream()
					.filter(item -> item.code() == proxyId)
					.findFirst().orElseThrow(RuntimeException::new);
		}
		return result;
	}

	private static Proxy create(JSONObject provinces) {
		return new Proxy(provinces);
	}

	public static Proxy provinces() {
		return create(JSON.parseObject(com.minelx.util.Files.toString("/proxies.json")));
	}
}
